# -*- coding:utf-8 -*-
import os
import socket
import json
import httplib
import urllib2
import urllib
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom
import shutil
from os.path import getsize


def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :
            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''
            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''

            index   = data.rfind('itemId')
            if index != -1:
                index_right = data.find('</integer>', index)
                itunesid = data[index: index_right]
                itunesid = itunesid.replace("itemId</key>" , '').replace("<integer>", "").strip()
            else:
                itunesid = ''
            
            return  version,bundleVersion,itunesid
        else:
            return '','',''
    except:
        return '','',''

private_sign = "%$@#%$#%^$#%$#";

root_path = 'd:\\'
root_path = root_path.replace("\\" , "/")

rsync_path = root_path
rsync_path = rsync_path.replace(":" , "")

src_path  = root_path+"/ipas_e/"
dst_path  = root_path+"/ipas_sign_bak/"

download_domain = "download.xyzs.com"

post_url = 'http://admin.xyzs.com/upscript/server_s_script.php'
count_num = 0
while True:

    datetime_now = datetime.datetime.now()
    datetime_now = datetime_now.strftime("%Y-%m-%d")

    listfile=os.listdir(src_path)
    if len(listfile) > 0:
        for line in listfile:
            if line.rfind('.ipa') != -1:
                return_value = get_version(unicode( src_path+line , "GBK" ))
                version_j    = return_value[0]
                bundleVersion_j = return_value[1]
                itunesid     = return_value[2]
                if itunesid != '':

                    datetime_time = datetime.datetime.now()
                    datetime_time = datetime_time.strftime("%Y-%m-%d %H:%M:%S")
                    print "====>>>>>>>>>>>" + datetime_time 
                    m = hashlib.md5(str(itunesid)) 
                    m.digest()
                    md5_str = m.hexdigest()
                    str1 = md5_str[0: 2]
                    str2 = md5_str[2: 4]

                    local_file = "/cygdrive/"+rsync_path+"/ipas_e/"+line

                    # rsync 上传文件 到 制定目录 
                    print "rsync -av --port=8733 "+local_file+" kingnet@192.168.12.61::upload_ipas/ipas/"+str1+"/"+str2+"/"
                    os.system("rsync -av --port=8733 "+local_file+" kingnet@192.168.12.61::upload_ipas/ipas/"+str1+"/"+str2+"/")

                    download_path = "/ipas/"+str1+"/"+str2+"/"+str(md5_str) + str2 + str1 + "_s.ipa"

                    # 这里休息 5 秒钟 , 确保rsync 同步过去 
                    time.sleep(5)

                    # 读取本地文件大小
                    local_file2 = src_path + line
                    size_local = getsize(local_file2)
                    size_local = str(size_local)

                    # 读取CDN上文件大小，版本号为当前时间戳，判断文件大小是否一直，如果一直就处理后面的逻辑，不一致就跳过该文件
                    conn = httplib.HTTPConnection(download_domain)
                    conn.request("GET", download_path+"?t="+str(datetime_now))
                    r    =conn.getresponse()
                    size_remote = r.getheader("content-length")

                    if size_local == size_remote:
                        print '------file-same-----'
                    else:
                        commom_log('rsync_upload_failed.log', local_file+"\n" , write_type='a')
                        continue

                    m = hashlib.md5(str(private_sign + itunesid))
                    m.digest()
                    sign = m.hexdigest()

                    parameters = {'sign' : sign , 'itunesid':itunesid , 'version_s':version_j , 'bundleVersion_s':bundleVersion_j}
                    data       = urllib.urlencode(parameters)
                    request    = urllib2.Request(post_url, data)
                    response   = urllib2.urlopen(request)
                    page       = response.read(200000)
                    print page # 获取返回值

                    m = hashlib.md5(str(version_j) + str(bundleVersion_j))
                    m.digest()
                    v_params = m.hexdigest()
                    download_url = 'http://'+download_domain + download_path+'?v='+v_params
                    try:
                        print "start clear CDN :" + download_url + "\n"
                        parameters = {'username' : 'xyzs' , 'password':'xyzs123' , 'type':1 , 'url':download_url}
                        data       = urllib.urlencode(parameters)
                        request    = urllib2.Request('http://pushdx.dnion.com/cdnUrlPush.do', data)
                        response   = urllib2.urlopen(request)
                        page       = response.read(200000)
                        print page
                        print "end Clear CDN \n"    
                    except:
                        print 'sleep 5 ms'
                        time.sleep(60)
                        parameters = {'username' : 'xyzs' , 'password':'xyzs123' , 'type':1 , 'url':download_url}
                        data       = urllib.urlencode(parameters)
                        request    = urllib2.Request('http://pushdx.dnion.com/cdnUrlPush.do', data)
                        response   = urllib2.urlopen(request)
                        page       = response.read(200000)
                        print page
                        print "end Clear CDN \n"

                    shutil.move(src_path+line , dst_path + line)

                    count_num += 1
                    print count_num
                    # commom_log('sign_success_'+datetime_now+'.log' , itunesid + "---" + src_path + line +  "\n" , 'a')
                    # sys.exit()
                    time.sleep(5)
                else:
                    # 读取文件失败
                    print "itunesid is null\n"
                    # commom_log('sign_error_'+datetime_now+'.log' , itunesid + "---" + src_path + line +  "\n" , 'a')
        else:
            print "wait 10 min ..."
            time.sleep(10)
